//
//  RDBloodSugarTagDBManager.m
//  ReverseDiabetes
//
//  Created by 王佩璇 on 2024/8/30.
//

#import "RDBloodSugarTagDBManager.h"

#define TableName(tablename) [NSString stringWithFormat:@"%@",tablename]
static NSString *dbFileName = @"sugar-tag.sqlite";
@implementation RDBloodSugarTagDBManager
static RDBloodSugarTagDBManager *_instance = nil;

#pragma mark =============== init ===============
+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(_instance == nil) {
            _instance = [[RDBloodSugarTagDBManager alloc] init];
        }
    });
    return _instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    });
    return _instance;
}

- (instancetype)init {
    if(self = [super init]) {
#if TARGET_IPHONE_SIMULATOR
        [self.queue inDatabase:^(FMDatabase * _Nonnull db) {}];
#else
        // 加密数据库文件
        NSString *encryptKey = @"RDBloodSugarTagDBManagerKey";
        [self.queue inDatabase:^(FMDatabase * _Nonnull db) {
            // 加密数据库文件
            [db setKey:encryptKey];
        }];
#endif
        
        
    }
    return self;
}
- (FMDatabaseQueue *)queue {
    if (!_queue) {
        NSString *dbpath = [self getDBPath];
        NSLog(@"-----%@",dbpath);
        ///创建数据库及线程队列
        _queue = [FMDatabaseQueue databaseQueueWithPath:dbpath];
    }
    return _queue;
}

- (NSString *)getDBPath {
    NSString *dbPath = [[NSBundle mainBundle] pathForResource:@"sugar-tag" ofType:@"sqlite"];
    return dbPath;
}





- (NSMutableArray *)getAllTag{
    @synchronized (self) {
        NSMutableArray *dataArray = [NSMutableArray array];
        
        NSString *sql = [NSString stringWithFormat:@"select * from %@ order by %@ asc",
                         TableName(Table_BloodSugarTag),
                         Table_BloodSugarTag_Tag_Id
        ];
        [_queue inDatabase:^(FMDatabase *db) {
            FMResultSet *rs = [db executeQuery:sql];
            
            while ([rs next]) {
                @autoreleasepool {

                    RDBloodSugarTag *model = [RDBloodSugarTag new];

                   
                    if (![rs columnIsNull:Table_BloodSugarTag_Tag_Name]) {
                        model.tag_name = [rs stringForColumn:Table_BloodSugarTag_Tag_Name];
                    }
                    
                    if (![rs columnIsNull:Table_BloodSugarTag_Tag_Id]) {
                        model.tag_id = [NSNumber numberWithInt:[rs stringForColumn:Table_BloodSugarTag_Tag_Id].intValue];
                    }
     
                    [dataArray addObject:model];
                }
            }
            if (rs) {
                [rs close];
            }
        }];
        
        return dataArray;
    }
}



@end
